<template>
  <div class="notification-center">
    <!-- 头部：标题 + 筛选 + 统计 -->
    <div class="notification-header">
      <h2>消息中心</h2>
      <div class="notification-stats">
        <el-badge :value="stats.totalUnreadCount" :hidden="!stats.hasUnread">
          <span>全部消息</span>
        </el-badge>
      </div>
    </div>

    <!-- 筛选标签 -->
    <div class="notification-tabs">
      <el-radio-group v-model="queryParams.type" @change="handleTypeChange">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="LIKE">
          点赞
          <el-badge
            :value="stats.likeUnreadCount"
            :hidden="!stats.likeUnreadCount"
          />
        </el-radio-button>
        <el-radio-button label="COMMENT">
          评论
          <el-badge
            :value="stats.commentUnreadCount"
            :hidden="!stats.commentUnreadCount"
          />
        </el-radio-button>
        <el-radio-button label="FOLLOW">
          关注
          <el-badge
            :value="stats.followUnreadCount"
            :hidden="!stats.followUnreadCount"
          />
        </el-radio-button>
        <el-radio-button label="SYSTEM">系统通知</el-radio-button>
      </el-radio-group>

      <el-radio-group
        v-model="queryParams.isRead"
        class="read-filter"
        @change="handleReadStatusChange"
      >
        <el-radio-button :label="null">全部</el-radio-button>
        <el-radio-button :label="0">未读</el-radio-button>
        <el-radio-button :label="1">已读</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 通知列表（聚合模式 - 支持折叠/展开） -->
    <div v-loading="loading" class="notification-list">
      <div
        v-for="group in notificationGroups"
        :key="group.groupKey"
        class="notification-group-item"
        :class="{
          unread: group.unreadCount > 0,
          expanded: expandedGroups[group.groupKey]
        }"
      >
        <!-- 聚合通知头部 -->
        <div class="group-header" @click="toggleGroupExpand(group)">
          <!-- 发送者头像组 -->
          <div class="sender-avatars">
            <el-avatar
              v-for="(sender, index) in group.senders.slice(0, 3)"
              :key="sender.userId"
              :src="sender.avatar"
              :style="{
                zIndex: 3 - index,
                marginLeft: index > 0 ? '-10px' : '0'
              }"
              size="medium"
            >
              {{ sender.nickName?.charAt(0) }}
            </el-avatar>
            <span v-if="group.otherSendersCount > 0" class="other-count">
              +{{ group.otherSendersCount }}
            </span>
          </div>

          <!-- 通知内容 -->
          <div class="notification-content">
            <div class="notification-title">
              {{ group.aggregatedTitle }}
            </div>
            <div v-if="group.target" class="notification-target">
              <span class="target-title">{{ group.target.title }}</span>
              <p v-if="group.target.contentSummary" class="target-summary">
                {{ group.target.contentSummary }}
              </p>
            </div>
            <div class="notification-time">
              {{ formatTime(group.latestTime) }}
            </div>
          </div>

          <!-- 未读标记 + 操作按钮 -->
          <div class="notification-actions">
            <el-badge
              :value="group.unreadCount"
              :hidden="group.unreadCount === 0"
            />
            <el-button
              v-if="group.unreadCount > 0"
              type="text"
              size="small"
              @click.stop="handleMarkGroupAsRead(group)"
            >
              标为已读
            </el-button>
            <!-- 展开/收起按钮 -->
            <el-button
              type="text"
              size="small"
              @click.stop="toggleGroupExpand(group)"
            >
              {{ expandedGroups[group.groupKey] ? "收起" : "展开" }}
              <el-icon>
                <component
                  :is="expandedGroups[group.groupKey] ? 'ArrowUp' : 'ArrowDown'"
                />
              </el-icon>
            </el-button>
          </div>
        </div>

        <!-- 展开的详细列表 -->
        <transition name="expand">
          <div
            v-if="expandedGroups[group.groupKey]"
            v-loading="detailLoadingMap[group.groupKey]"
            class="group-details"
          >
            <div
              v-for="detail in groupDetailsMap[group.groupKey]"
              :key="detail.id"
              class="detail-item"
              :class="{ unread: !detail.isRead }"
            >
              <el-avatar :src="detail.sender?.avatar" size="small">
                {{ detail.sender?.nickName?.charAt(0) }}
              </el-avatar>
              <div class="detail-content">
                <div class="detail-header">
                  <span class="sender-name">{{ detail.sender?.nickName }}</span>
                  <span class="action-text">{{ detail.actionText }}</span>
                  <span class="detail-time">{{
                    formatTime(detail.createTime)
                  }}</span>
                </div>
              </div>
              <div v-if="!detail.isRead" class="unread-dot" />
            </div>
          </div>
        </transition>
      </div>

      <!-- 空状态 -->
      <el-empty
        v-if="!loading && notificationGroups.length === 0"
        description="暂无通知"
      />
    </div>

    <!-- 分页 -->
    <div class="notification-pagination">
      <el-pagination
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import {
  getGroupedNotifications,
  getGroupDetails,
  markGroupAsRead,
  getNotificationStats
} from "@/api/notification";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";

// 响应式数据
const loading = ref(false);
const notificationGroups = ref([]);
const total = ref(0);

// 展开状态管理
const expandedGroups = ref({}); // { groupKey: true/false }
const groupDetailsMap = ref({}); // { groupKey: [details] }
const detailLoadingMap = ref({}); // { groupKey: true/false }

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 20,
  type: "",
  isRead: null
});

// 统计数据
const stats = ref({
  totalUnreadCount: 0,
  likeUnreadCount: 0,
  commentUnreadCount: 0,
  followUnreadCount: 0,
  hasUnread: false
});

// 加载通知列表
const loadNotifications = async () => {
  loading.value = true;
  try {
    const response = await getGroupedNotifications(queryParams);
    if (response.code === 200) {
      notificationGroups.value = response.data.records;
      total.value = response.data.total;
    }
  } catch (error) {
    ElMessage.error("加载通知失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await getNotificationStats();
    if (response.code === 200) {
      stats.value = response.data;
    }
  } catch (error) {
    console.error("加载统计失败", error);
  }
};

// 切换分组展开/收起
const toggleGroupExpand = async group => {
  const groupKey = group.groupKey;

  // 如果已展开，则收起
  if (expandedGroups.value[groupKey]) {
    expandedGroups.value[groupKey] = false;
    return;
  }

  // 如果未展开，则展开并加载详情
  expandedGroups.value[groupKey] = true;

  // 如果已经加载过详情，直接显示
  if (groupDetailsMap.value[groupKey]) {
    return;
  }

  // 加载详情
  detailLoadingMap.value[groupKey] = true;
  try {
    const response = await getGroupDetails({
      type: group.type,
      targetType: group.targetType,
      targetId: group.targetId
    });
    if (response.code === 200) {
      groupDetailsMap.value[groupKey] = response.data;
    }
  } catch (error) {
    ElMessage.error("加载详情失败");
    console.error(error);
    // 加载失败时收起
    expandedGroups.value[groupKey] = false;
  } finally {
    detailLoadingMap.value[groupKey] = false;
  }
};

// 标记分组为已读
const handleMarkGroupAsRead = async group => {
  try {
    const response = await markGroupAsRead({
      type: group.type,
      targetType: group.targetType,
      targetId: group.targetId
    });
    if (response.code === 200) {
      ElMessage.success("已标记为已读");

      // 更新本地状态
      group.unreadCount = 0;
      group.allRead = true;

      // 如果该分组已展开，更新详情中的已读状态
      const groupKey = group.groupKey;
      if (groupDetailsMap.value[groupKey]) {
        groupDetailsMap.value[groupKey].forEach(detail => {
          detail.isRead = true;
        });
      }

      // 刷新统计
      await loadStats();
    }
  } catch (error) {
    ElMessage.error("操作失败");
    console.error(error);
  }
};

// 筛选类型变化
const handleTypeChange = () => {
  queryParams.current = 1;
  loadNotifications();
};

// 已读状态变化
const handleReadStatusChange = () => {
  queryParams.current = 1;
  loadNotifications();
};

// 分页变化
const handlePageChange = page => {
  queryParams.current = page;
  loadNotifications();
};

const handleSizeChange = size => {
  queryParams.size = size;
  queryParams.current = 1;
  loadNotifications();
};

// 格式化时间
const formatTime = time => {
  if (!time) return "";
  return formatDistanceToNow(new Date(time), {
    addSuffix: true,
    locale: zhCN
  });
};

// 初始化
onMounted(() => {
  loadNotifications();
  loadStats();
});
</script>

<style scoped lang="scss">
.notification-center {
  max-width: 1200px;
  padding: 20px;
  margin: 0 auto;

  .notification-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
    }
  }

  .notification-tabs {
    display: flex;
    justify-content: space-between;
    padding-bottom: 15px;
    margin-bottom: 20px;
    border-bottom: 1px solid #e8e8e8;

    .read-filter {
      margin-left: auto;
    }
  }

  .notification-list {
    min-height: 400px;
  }

  .notification-group-item {
    margin-bottom: 12px;
    overflow: hidden;
    background: #fff;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    transition: all 0.3s;

    &.unread {
      background: #f0f9ff;
      border-color: #409eff;
    }

    &.expanded {
      box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
    }

    .group-header {
      display: flex;
      align-items: flex-start;
      padding: 16px;
      cursor: pointer;
      transition: background 0.3s;

      &:hover {
        background: rgb(0 0 0 / 2%);
      }
    }

    .sender-avatars {
      position: relative;
      display: flex;
      align-items: center;
      margin-right: 16px;

      .el-avatar {
        border: 2px solid #fff;
      }

      .other-count {
        margin-left: 8px;
        font-size: 14px;
        color: #909399;
      }
    }

    .notification-content {
      flex: 1;
      min-width: 0;

      .notification-title {
        margin-bottom: 8px;
        font-size: 15px;
        font-weight: 500;
        color: #303133;
      }

      .notification-target {
        margin-bottom: 8px;

        .target-title {
          font-size: 14px;
          color: #409eff;
        }

        .target-summary {
          display: -webkit-box;
          margin: 4px 0 0;
          overflow: hidden;
          text-overflow: ellipsis;
          -webkit-line-clamp: 2;
          font-size: 13px;
          line-height: 1.5;
          color: #909399;
          -webkit-box-orient: vertical;
        }
      }

      .notification-time {
        font-size: 12px;
        color: #c0c4cc;
      }
    }

    .notification-actions {
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: flex-end;
    }
  }

  .notification-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  // 展开的详情列表
  .group-details {
    max-height: 400px;
    overflow-y: auto;
    background: #fafafa;
    border-top: 1px solid #e8e8e8;

    .detail-item {
      position: relative;
      display: flex;
      align-items: center;
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f0;
      transition: background 0.3s;

      &:hover {
        background: #fff;
      }

      &:last-child {
        border-bottom: none;
      }

      &.unread {
        background: #f0f9ff;
      }

      .el-avatar {
        flex-shrink: 0;
        margin-right: 12px;
      }

      .detail-content {
        flex: 1;
        min-width: 0;

        .detail-header {
          display: flex;
          gap: 8px;
          align-items: center;

          .sender-name {
            font-weight: 500;
            color: #303133;
          }

          .action-text {
            font-size: 14px;
            color: #606266;
          }

          .detail-time {
            margin-left: auto;
            font-size: 12px;
            color: #c0c4cc;
          }
        }
      }

      .unread-dot {
        position: absolute;
        top: 50%;
        right: 16px;
        width: 8px;
        height: 8px;
        background: #409eff;
        border-radius: 50%;
        transform: translateY(-50%);
      }
    }
  }

  // 展开/收起动画
  .expand-enter-active,
  .expand-leave-active {
    max-height: 400px;
    transition: all 0.3s ease;
  }

  .expand-enter-from,
  .expand-leave-to {
    max-height: 0;
    opacity: 0;
  }
}
</style>
